package com.fr.lintcode;

import java.util.HashSet;
import java.util.Set;

import org.junit.Test;

public class Q570 {

	/**
	 * @param n:   An integer
	 * @param str: a string with number from 1-n in random order and miss one number
	 * @return: An integer
	 */
	int rs = 0;
	public int findMissing2(int n, String str) {
		// write your code here
		if (n <= 0 || str == null) {
			return 0;
		}
		if (n == 1) {
			return 1;
		}
		Set<Integer> filter = new HashSet<>();
		for(int i = 1; i <= n; i++) {
			filter.add(i);
		}
		boolean used[] = new boolean[n];
		int findNum = 0;
		int index = 0;
		search(index, findNum, filter, n, str, used);
		return rs;
	}

	private void search(int index, int findNum, Set<Integer> filter, int n, String str, boolean used[]) {
		// TODO Auto-generated method stub
		if (rs > 0) {
			return;
		}
		if(index > 0 && !used[index -1]) {
			return;
		}
		if (filter.size() == 1) {
			for(int f : filter) {
				rs = f;
			}
			return;
		}
		int i = str.charAt(index) - '0';
		if(i == 0) {
			return;
		}
		if (i <= n && filter.contains(i)) {
			findNum++;
			filter.remove(i);
			used[index] = true;
			search(index + 1, findNum, filter, n, str, used);
			findNum--;
			filter.add(i);
			used[index] = false;
		}
		if(index + 1 < n) {
			i = Integer.parseInt(str.substring(index, index + 2));
			if (i <= n && filter.contains(i)) {
				findNum++;
				filter.remove(i);
				used[index] = true;
				used[index+1] = true;
				search(index + 2, findNum, filter, n, str, used);
				findNum--;
				filter.add(i);
				used[index] = false;
				used[index+1] = false;
			}
		}
	}
	
	@Test
	public void testA() {
		int rs = findMissing2(20, "19201234567891011121314151618");
		System.out.println(rs);

	}

}
